package com.example.demo.controller;

import com.example.demo.constant.User;
import com.example.demo.exception.MyException;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * Created on 2019/9/9.
 *
 * @author Grak
 * @since 1.0
 */
@RestController("/user")
public class UserController {

    private Map<String,User> userList = new HashMap<>();

    @ApiOperation(value = "自定义异常",notes = "通过配置异常类，捕获全局异常信息！！")
    @RequestMapping(value = "/errorJson",method = RequestMethod.GET)
    public String errorJson() throws MyException {
        throw new MyException("自定义异常！");
    }

    @ApiOperation(value = "获取用户信息",notes = "通过用户名字作为key，获取详细信息")
    @ApiImplicitParam(name = "name",value = "用户姓名",required = true, dataType = "String")
    @RequestMapping(value = "/find",method = RequestMethod.GET)
    public User getUser(@ModelAttribute String name){
        return userList.get(name);
    }

    @ApiOperation(value = "添加用户信息",notes = "直接使用用户实体类创建，里面名字是必须填写的。")
    @ApiImplicitParam(name = "user",value = "用户实体类",required = true, dataType = "User")
    @RequestMapping(value = "/add",method = RequestMethod.POST)
    public String addUser(@ModelAttribute User user){
        if(user != null){
            userList.put(user.getName(),user);
            return "success";
        }else {
            return "玩家数据异常！！";
        }
    }

    @ApiOperation(value = "删除用户信息",notes = "通过用户名字作为key，年龄只是说明可使用多个参数。没具体作用！")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "age",value = "用户年龄",required = false, dataType = "Integer"),
            @ApiImplicitParam(name = "name",value = "用户姓名",required = true, dataType = "String")
    })
    @RequestMapping(value = "/delete",method = RequestMethod.GET)
    public int deleteUser(@PathVariable String name,@PathVariable int age){
        userList.remove(name);
        return userList.size();
    }

    @ApiOperation(value = "修改用户信息",notes = "直接使用名字修改，名字不能改！")
    @ApiImplicitParam(name = "user",value = "用户实体类",required = true, dataType = "User")
    @RequestMapping(value = "/modify",method = RequestMethod.POST)
    public String updateUser(@ModelAttribute User user){
        User userSelf = userList.get(user.getName());
        if(userSelf != null){
            if(user.getName() != null){
                userSelf.setName(user.getName());
            }
            if(user.getAge() > 0){
                userSelf.setAge(user.getAge());
            }
            if(user.getAddress() != null){
                userSelf.setAddress(user.getAddress());
            }
            if(user.getDescription() != null){
                userSelf.setDescription(user.getDescription());
            }
            return "success";
        }else {
            return "修改参数异常！！";
        }
    }
}
